using System;
using System.Collections;
using UnityEngine;
using QFramework;

namespace Survivor
{
	public partial class Player : ViewController
	{
		public float MovementSpeed = 3f;

		public static Player Default;
		
		private static readonly int IsRun = Animator.StringToHash("IsRun");

		private void Awake()
		{
			Default = this;
		}

		private void OnDestroy()
		{
			Default = null;
		}

		void Start()
		{
			Global.Hp.RegisterWithInitValue((value) =>
			{
				HpBar.fillAmount = value /(float)Global.MaxHp.Value;
			}).UnRegisterWhenGameObjectDestroyed(this);
		}

		private void Update()
		{
			var horizon = Input.GetAxis("Horizontal");
			var vertex = Input.GetAxis("Vertical");
			var isMove = !Mathf.Approximately(horizon + vertex, 0);
			Anim.SetBool(IsRun,isMove);
			if (isMove)
			{
				Sprite.transform.rotation = Quaternion.Euler(0, horizon < 0 ? 180 : 0, 0);
			}

			var dirction = new Vector2(horizon, vertex).normalized;
			 SelfRigidbody2D.velocity = ((dirction * (MovementSpeed * Global.MoveSpeedRate.Value)));
		}
		
		public void Hurt(int damage)
		{
			Global.Hp.Value -= damage;
			if (Global.Hp.Value <= 0)
			{
				AudioKit.PlaySound("Die");
				Player.Default = null;
				
				this.DestroyGameObjGracefully();
				UIKit.OpenPanel<UIGameOverPanel>();
			}
			else
			{
				if (_isHurtPerforming)
				{
					_hurtPerformDuration = 0.3f;
				}
				else
				{
					StartCoroutine(IHurtPerform());
				}
				// AudioKit.PlaySound("Hurt");
			}
		}

		private bool _isHurtPerforming;
		private float _hurtPerformDuration;
		private IEnumerator IHurtPerform()
		{
			_isHurtPerforming = true;
			_hurtPerformDuration = 0.3f;
			Sprite.color = Color.red;
			
			while (_hurtPerformDuration > 0)
			{
				_hurtPerformDuration -= Time.deltaTime;
				yield return null;
			}

			_isHurtPerforming = false;
			Sprite.color = Color.white;
		}
	}
}
